﻿package rob.entity{
	import flash.display.Sprite;
	import flash.geom.Point;
	//import flash.filters.*;
	import rob.data.Vert3d;
	import rob.data.Vect3d;
	import rob.maths.VectorMaths;
	
	// side of a structure: consists of ref to points & a normal
	public class Side extends Sprite{
		private var _pntMcs:Array;
		private var _normal:Vect3d, _pnt3d:Vert3d;
		private var _floors:Array, _depth:Number;
		
		public function Side(pntMcs:Array,floors:Array,pnt3d:Vert3d,swapNormalDir:Boolean):void{
			// expected order: base i -> top i -> top (i+1) -> base (i+1)
			_pntMcs = pntMcs;
			// use anti-clockwise convention to compute normal
			// need relative positions in great-grandparent
			// which is scene_mc because haven't added yet to _scene
			// still suffices to compute normals
			var tang:Point = _getGlobPnt(_pntMcs[3]).subtract(_getGlobPnt(_pntMcs[0]));
			_normal = new Vect3d(-tang.y,0,tang.x);
			// swap normal direction if necessary
			if(swapNormalDir) VectorMaths.negate(_normal);
			VectorMaths.normalise(_normal);
			// floors are just base and top mcs, need to pick up their scalings when rendering
			_floors = floors;
			// also needs a single 3d point to test visibility (together with normal)
			// we are sent the position of base...
			_pnt3d = pnt3d;
		
		}
		
		// draw the side
		public function render():void{
			var scb:Number = _floors[0].scaleX, sct:Number = _floors[1].scaleX;
			var tx:Number = _floors[1].x, ty:Number = _floors[1].y;
			with(this.graphics){
				clear();
				lineStyle(0,0);
				beginFill(0x101010,1);
				moveTo(scb * _pntMcs[0].x, scb * _pntMcs[0].y);
				lineTo(tx + sct * _pntMcs[1].x , ty + sct * _pntMcs[1].y);
				lineTo(tx + sct * _pntMcs[2].x , ty + sct * _pntMcs[2].y);
				lineTo(scb * _pntMcs[3].x,scb * _pntMcs[3].y);
				lineTo(scb * _pntMcs[0].x, scb * _pntMcs[0].y);
			}
		}
		
		// compute point relative to great-grandparent's coordinate system
		private function _getGlobPnt(pntMc:Sprite):Point{
			var ggp:Sprite = pntMc.parent.parent.parent;
			var p:Point = new Point(pntMc.x,pntMc.y);
			p = pntMc.parent.localToGlobal(p);
			p = ggp.globalToLocal(p);
			return p;
		}

		public function get pnt3d():Vert3d{return _pnt3d;}
		public function get normal():Vect3d{return _normal;}
		public function get depth():Number{return _depth;}
		
		public function set depth(d:Number):void{_depth = d;}
	}
}